package com.pci.netty.handler;

import cn.hutool.core.codec.BCD;
import com.pci.netty.business.IHandler;
import com.pci.netty.dto.RequestPayload;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
public class CommadHandler extends SimpleChannelInboundHandler<RequestPayload> {
    private Map<String, IHandler> map;

    public CommadHandler(Map<String, IHandler> map) {
        this.map = map;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RequestPayload dto) throws Exception {
        try {
            RequestPayload.Header header = RequestPayload.analysis(dto.getHead());
            String msgCode = BCD.bcdToStr(header.getMsgCode());
            IHandler handler = map.get(msgCode);
            if (handler == null) {
                log.error("消息类型:{},未找到相关处理器", msgCode);
            } else {
                handler.handler(dto, ctx);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("处理异常{}", e.getMessage());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("异常关闭连接,{}", cause.getMessage());
        ctx.close();
    }

}
